package mfuny.ggongal.admin.login;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mfuny.ggongal.admin.Server;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ibatis.sqlmap.client.SqlMapClient;

@Service
public class LoginService extends HandlerInterceptorAdapter {
	SqlMapClient sqlMapper;
	
	ModelAndView mav;
	HashMap<String, String> map;
	
	public LoginService() throws Exception {
		sqlMapper = Server.getSqlMapper( );
		
		mav = new ModelAndView();
		map = new HashMap<String, String>();
	}
	
	public ModelAndView login() throws Exception {
		mav.clear( );
		mav.setViewName( "/login/login.ga" );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView loginPro( String id, String password, HttpSession session ) throws Exception {
		map = (HashMap<String, String>) sqlMapper.queryForObject( "admin_select", null );
		String adminId = map.get( "id" );
		String adminPass = map.get( "password" );
		mav.clear( );
		if ( !id.equals( adminId )) {
			mav.addObject( "msg", "ID가 일치하지 않습니다." );
			mav.setViewName( "/login/loginFailed.ga" );
			return mav;
		}
		if ( !password.equals( adminPass )) {
			mav.addObject( "msg", "비밀번호가 일치하지 않습니다." );
			mav.setViewName( "/login/loginFailed.ga" );
			return mav;
		}
		session.setAttribute( "admin", id );
		mav.setViewName( "/login/login.ga" );
		return mav;
	}
	
	public ModelAndView logoutPro( HttpSession session ) throws Exception {
		session.removeAttribute( "admin" );
		mav.clear( );
		mav.addObject( "msg", "정상적으로 로그아웃 되었습니다." );
		mav.setViewName( "/login/loginFailed.ga" );
		return mav;
	}
	
	@Override
	public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {
//		if ( "/admin/login.ga".equals( request.getRequestURI( )) ) { return true; }
//		if ( "/admin/loginPro.ga".equals( request.getRequestURI( )) ) { return true; }
		boolean result = false;
		HttpSession session = request.getSession( );
		if ( session == null ) {
			response.sendRedirect( "/ggongal_admin/login.ga" );
			return result;
		}
		String sessionId = (String) session.getAttribute( "admin" );
		if ( sessionId == null ) {
			response.sendRedirect( "/ggongal_admin/login.ga" );
			return result;
		}
		result = true;
		return result;
	}
}
